package com.lc.user.express.ordering;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.R;
import com.lc.user.express.adapter.SearchAddrAdapter;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.model.AddrModel;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.Logger;
import com.lc.user.express.utils.PublicMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/3/18.搜索地址
 */
public class SearchAddrActivity extends BaseSecondActivity implements TextWatcher, Inputtips.InputtipsListener {
    public static final int TYPE_S = 0x22;//始发地
    public static final int TYPE_E = 0x24;//终点
    private AutoCompleteTextView et_searchText;// 输入搜索关键字
    private ListView lv;//搜索列表
    private List<AddrModel> list = new ArrayList<>();//搜索列表数据
    private SearchAddrAdapter adapter;//搜索
    private RelativeLayout rl_contact;//联系人布局
    private boolean is = true;//列表是否显示标志位，用于点选之后隐藏列表

    //发货人信息
    private EditText et_name;//联系人姓名
    private EditText et_mobile;//联系热电话
    private EditText et_dizhi;
    private AddrModel model = new AddrModel();//地址model
    //输入表情前的光标位置
    private int cursorPos;
    //输入表情前EditText中的文本
    private String inputAfterText;
    //是否重置了EditText的内容
    public boolean resetText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_addr);
        initView();
    }

    private void initView() {
        ((TextView) findViewById(R.id.tv_public)).setOnClickListener(this);
        et_mobile = (EditText) findViewById(R.id.et_mobile);


        //发货人信息
        et_name = (EditText) findViewById(R.id.et_name);
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count >= 2) {//表情符号的字符长度最小为2
                    CharSequence input = s.subSequence(cursorPos, cursorPos + count);
                    if (containsEmoji(input.toString())) {
                        resetText = true;
                        Toast.makeText(getApplicationContext(), "不支持输入表情符号", Toast.LENGTH_SHORT).show();
                        //是表情符号就将文本还原为输入表情符号之前的内容
                        et_name.setText(inputAfterText);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        et_dizhi = (EditText) findViewById(R.id.dizhi);
        rl_contact = (RelativeLayout) findViewById(R.id.rl_contact);
        et_searchText = (AutoCompleteTextView) findViewById(R.id.keyWord);



        et_searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count >= 2) {//表情符号的字符长度最小为2
                    CharSequence input = s.subSequence(cursorPos, cursorPos + count);
                    if (containsEmoji(input.toString())) {
                        resetText = true;
                        Toast.makeText(getApplicationContext(), "不支持输入表情符号", Toast.LENGTH_SHORT).show();
                        //是表情符号就将文本还原为输入表情符号之前的内容
                        et_searchText.setText(inputAfterText);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_dizhi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count >= 2) {//表情符号的字符长度最小为2
                    CharSequence input = s.subSequence(cursorPos, cursorPos + count);
                    if (containsEmoji(input.toString())) {
                        resetText = true;
                        Toast.makeText(getApplicationContext(), "不支持输入表情符号", Toast.LENGTH_SHORT).show();
                        //是表情符号就将文本还原为输入表情符号之前的内容
                        et_dizhi.setText(inputAfterText);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });




        et_searchText.addTextChangedListener(this);

        lv = (ListView) findViewById(R.id.lv);
        adapter = new SearchAddrAdapter(cnt, list);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                lv.setVisibility(View.GONE);
                rl_contact.setVisibility(View.VISIBLE);
                et_searchText.setText(list.get(position).getAddr());
                et_searchText.setSelection(et_searchText.getText().toString().length());
                is = false;

                model.setLng(list.get(position).getLng());
                model.setLat(list.get(position).getLat());
                model.setAddr(list.get(position).getAddr());
                model.setPoint(list.get(position).getPoint());
            }
        });
        initDataView();
        showKeyboad();

    }

    /**
     * 分类型初始化 始发地 途径地 目的地
     */
    private void initDataView() {
        if (getIntent().getFlags() == TYPE_S) {
            setTitle("发货信息");
            et_searchText.setHint("请输入始发地");
        } else if (getIntent().getFlags() == TYPE_E) {
            setTitle("收货信息");
            et_searchText.setHint("请输入目的地");
        }
        model = (AddrModel) getIntent().getSerializableExtra("addr"); //修改地址信息时默认之前地址信息
        if (!TextUtils.isEmpty(model.getAddr())) {

            et_searchText.setText(model.getAddr());
            et_name.setText(model.getName());
            et_mobile.setText(model.getMobile());
            et_searchText.setSelection(et_searchText.getText().toString().length());
            is = false;
            rl_contact.setVisibility(View.VISIBLE);
            lv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_public:

                if (!PublicMethod.isMobilePhone(et_mobile.getText().toString().trim())) {
                    GetToast.useString(cnt, "请输入正确的手机号码");
                    return;
                }
                model.setAddr(et_searchText.getText().toString() + et_dizhi.getText());
                System.out.println(model.getAddr());
                model.setName(et_name.getText().toString().trim());
                model.setMobile(et_mobile.getText().toString().trim());

                if (OrderInfoCompleteActivity.onAddrChange != null) {
                    OrderInfoCompleteActivity.onAddrChange.onAddr(model);
                }
                if (AddUsedRouteActivity.onAddrChange != null) {
                    AddUsedRouteActivity.onAddrChange.onAddr(model);
                }
                finish();
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        // InputtipsQuery inputquery = new InputtipsQuery(newText, AppContext.myPreferences.getCity() + " ");
        //  InputtipsQuery inputquery = new InputtipsQuery(" ", newText);
        InputtipsQuery inputquery = new InputtipsQuery(AppContext.myPreferences.getCity() + " " +newText,"");


        Inputtips inputTips = new Inputtips(SearchAddrActivity.this, inputquery);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (TextUtils.isEmpty(et_searchText.getText().toString().trim())) {
            list.clear();
            adapter.updateListView(list);
            return;
        }
        if (rCode == 1000) {// 正确返回
            if (is) {
                lv.setVisibility(View.VISIBLE);
                list.clear();
                for (int i = 0; i < tipList.size(); i++) {
//                    Log.i("lll", "getName=" + tipList.get(i).getName() + "getDistrict=" + tipList.get(i).getDistrict() + "getPoint=" + tipList.get(i).getPoint());
                    if (tipList.get(i).getPoint() != null) {
                        AddrModel model = new AddrModel();
                        model.setAddr(tipList.get(i).getName());
                        model.setDistrict(tipList.get(i).getDistrict());
                        model.setLng(tipList.get(i).getPoint().getLongitude());
                        model.setLat(tipList.get(i).getPoint().getLatitude());
                        model.setPoint(tipList.get(i).getPoint().toString());
                        list.add(model);
                    }

                }

                adapter.updateListView(list);
            } else {
                rl_contact.setVisibility(View.VISIBLE);
                lv.setVisibility(View.GONE);
            }
            is = true;
        } else {
            Logger.eLog("lll", "rCode=" + rCode);
        }


    }

    private void showKeyboad() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {



                InputMethodManager inputManager = (InputMethodManager) et_searchText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(et_searchText, 0);
            }

        }, 500);
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }
}
